let pageData = {
    "records": [
        {
            "id": 1,
            "code": "yinliao",
            "name": "零食专卖店",
            "detail": "零食专卖店",
            "contact": "杨先生",
            "tel": "13112341234",
            "address": "全国",
            "img": "",
            "status": null,
            "createTime": null
        }
    ],
    "total": 1,
    "size": 8,
    "current": 1,
    "orders": [],
    "optimizeCountSql": true,
    "searchCount": true,
    "countId": null,
    "maxLimit": null,
    "pages": 1
}
let $entry_provider = $('#admin-card-provider-list-entry')
let $entry_pages = $('#admin-card-provider-pages-entry')
function renderProviders(providers, delay){
    $entry_provider.html('')
    setTimeout(function (){
        providers.forEach(function (provider, index){
            let fn_modify = "renderEditModal(this," + provider['id'] + ")"
            let fn_remove = "removeProvider(" + provider['id'] + ")"
            $entry_provider.append(`
            <tr valign="baseline">
                <td><input type="checkbox" class="cb_provider" data-id="${provider['id']}" style="width: 20px; height: 20px;"></td>
                <td>${provider['id']}</td>
                <td>${provider['name']}</td>
                <td>${provider['detail']}</td>
                <td>${provider['contact']}</td>
                <td>${provider['tel']}</td>
                <td>${provider['address']}</td>
                <td>
                     <button class="btn btn-primary w-25" data-bs-toggle="modal" data-bs-target="#modal-show" onclick="${fn_modify}">查看</button>
                     <button class="btn btn-warning w-25" data-bs-toggle="modal" data-bs-target="#modal-base" onclick="${fn_modify}">编辑</button>
                     <button class="btn btn-danger w-25" onclick="${fn_remove}">删除</button>
                </td>
          </tr>
        `)
        })
    }, delay)
}
// 编辑某个用户的角色时渲染修改的模态框
function renderEditModal(btn, providerId){
    renderModal(btn, ajaxPostJSON('/provider/query/' + providerId))
}
function renderPage(page){
    $entry_pages.html('')
    let $perPage = $(`<li></li>`)
    // 渲染尾部
    let $tail = `<li class="align-self-center r">
                &nbsp;&nbsp;到第&nbsp;&nbsp;
            </li>
            <li class="align-self-center">
                <input id="admin-user-input-to-page" class="input-group" name="pageNum" size="5">
            </li>
            <li class="align-self-center">
                &nbsp;页&nbsp;
            </li>
            <li class="align-self-center">
                <button class="btn btn-outline-dark" onclick="toPage('admin-user-input-to-page', 1, ${page.pages})">确定</button>
            </li>`

    // 计算页数的渲染范围
    page.prePage = Math.max(1, page['current']- 1)
    page.nextPage = Math.min(page['pages'], page['current'] + 1)
    page.startPage = Math.max(1, page['current'] - 2)
    page.endPage = Math.min(page['pages'], page['current'] + 2)
    // 渲染每一页
    for (let i = page.startPage; i <= page.endPage; i++) {
        if(i === page.current){ // 渲染当前页，设置一个高亮的效果
            $perPage.append(`
            <li class="page-item mx-2 active" aria-current="page">
             <a class="page-link d-block" href="${paramUpdateCurrentParam('pageNum', i)}">${i}</a>
         </li>`)
        } else {
            $perPage.append(`
             <li class="page-item mx-2" aria-current="page">
                 <a class="page-link d-block" href="${paramUpdateCurrentParam('pageNum', i)}">${i}</a>
             </li>`
            )
        }
    }
    $entry_pages.html('')
    $entry_pages.html(`
            <ul class="pagination mx-auto justify-content-center">
            <li class="align-self-center me-3 rounded-3">
                    第 ${page.current} 页 &nbsp;&nbsp; 共 ${page.pages} 页
            </li>
            <li class="page-item ms-page">
                 <a class="page-link" href="${paramUpdateCurrentParam('pageNum', 1)}">
                    首页
                 </a>
            </li>
            <!--上一页-->
           <li class="page-item ms-page">
                <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page.prePage)}">上一页</a>
            </li>`
        + $perPage.html() + `
            <!--下一页-->
             <li class="page-item ms-page">
                <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page.nextPage)}">下一页</a>
            </li>
            <!--最后一页-->
             <li class="page-item ms-page" href="/index.html?pageNum=${page.pages}">
                  <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page.pages)}">末页</a>
             </li>` + $tail +
        `</ul>`)
    $('#textShowResult').text('共 ' + page.total + ' 条结果')

}
////////////////////// 功能函数区
///// 跳转到指定页
function toPage(inputId, mini, maxi){
    $input = $('#' + inputId)
    let page = $input.val()
    // 限制页面的范围
    page = Math.min(page, maxi)
    page = Math.max(page, mini)
    location.href = paramUpdateCurrentParam('pageNum', page)
}
///// 搜索
function searchProvider(btn){
    location.href = paramUpdateCurrentParam('name', $(btn).prev('input').val())
}
///// 保存修改
function saveEdit(){
    let result = ajaxPostUpdate({
        'url': '/provider/update',
        'data': $('#form-edit').serialize()
    })
    if(result['code'] === CODE_SUCCESS)
        ms_show_toast_callback(true, result['msg'], function (){
            location.reload()
        })
    else
        ms_show_toast(false, '权限不足')
}

///// 删除供应商
function removeProvider(id){
    let result = ajax('DELETE', '/provider/delete/' + id)
    if(result['code'] === CODE_SUCCESS){
        ms_show_toast_callback(true, result['msg'], function (){
            location.reload()
        })
    } else
        ms_show_toast(false,'权限不足')
}
// 删除多个供应商
function removeProviders(){
    ids = []
    // 获取选择的需要删除的供应商
    $('.cb_provider').each(function (){
        if($(this).prop('checked') === true){
            ids.push($(this).data('id'))
        }
    })
    if(ids.length === 0) { ms_show_toast(false, '请选择要删除的供应商') ; return }
    let result = ajax('DELETE', '/provider/delete/' + ids)
    if(result['code'] === CODE_SUCCESS){
        ms_show_toast_callback(true, result['msg'], function (){
            location.reload()
        })
    } else
        ms_show_toast(false, '权限不足')
}
// 添加供应商
function insertProvider(){
    let $form = $('#form-insert')
    let result = ajaxPostJSONByMap('/provider/insert', $form.serialize())
    if(result['code'] === CODE_SUCCESS){
        ms_show_toast_reload(true, result['msg'])
    }
    ms_show_toast(false, result['msg'])
}
// 全选
$('#cb_all').click(function (){
  $('.cb_provider').prop('checked', $(this).prop('checked'))
})
$(document).ready(function (){
    pageData = ajaxPostJsonByCurrentUrlParam('/provider/query')
    console.log(pageData)
    renderProviders(pageData['records'], 100)
    renderPage(pageData)
})